$(function () {
    $('#side-menu').metisMenu();
    $(window).bind("load resize", function () {
        var topOffset = 50;
        var width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
        if (width < 768) {
            $('div.navbar-collapse').addClass('collapse');
            topOffset = 100; // 2-row-menu
        } else {
            $('div.navbar-collapse').removeClass('collapse');
        }

        var height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1;
        height = height - topOffset;
        if (height < 1) height = 1;
        if (height > topOffset) {
            $("#page-wrapper").css("min-height", (height) + "px");
        }
    });

    var url = window.location, request = false;
    var element = $('ul.nav a').filter(function () {
        return this.href == url;
    }).addClass('active').parent();

    while (true) {
        if (element.is('li')) {
            element = element.parent().addClass('in').parent();
        } else {
            break;
        }
    }

    //表格自动化 DataTables
    var tableDom = $('.table-responsive table');
    if (tableDom.length > 0) {
        for (var i = 0; i < tableDom.length; i++) {
            var dom = tableDom[i];
            if (!$.fn.dataTable) {
                console.log('dataTable is not import.');
                break;
            }
            var url = $(dom).attr('data-url') || location.href,
                columns = $(dom).attr('data-cols') ? $(dom).attr('data-cols').split(',') : [],
                aoColumnsTmp = $(dom).attr('data-ac') ? $(dom).attr('data-ac').split(',') : [],
                columnsStyle = $(dom).attr('data-column-style') ? $(dom).attr('data-column-style').split(',') : [],
                autoWidth = !(columnsStyle.length > 0);
            csrf = $('input[name="_csrf"]').val(),
                aoColumns = [];

            while (columnsStyle.length < columns.length) {
                columnsStyle.push(null);
            }
            if (!url || !columns || !aoColumnsTmp || !csrf || !aoColumns) {
                continue;
            }
            for (var j = 0; j < aoColumnsTmp.length; j++) {
                aoColumns[j] = {sTitle: aoColumnsTmp[j]};
            }
            var dataOptions = {
                sErrMode: function (settings, tn, msg) {
                    console.log(settings, tn, msg);
                },
                dom: "<'row'<'col-sm-6'l><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'p>>",
                processing: false,
                pagingType: "full_numbers",
                serverSide: true,
                aoColumns: aoColumns,
                columns: columnsStyle,
                autoWidth: autoWidth,
                ajax: {
                    url: url,
                    type: 'post',
                    data: {col: columns, _csrf: csrf}
                },
                language: {
                    "sProcessing": "",
                    "sLengthMenu": "显示 _MENU_ 项结果",
                    "sZeroRecords": "没有匹配结果",
                    "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                    "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                    "sInfoPostFix": "",
                    "sSearch": "搜索:",
                    "sUrl": "",
                    "sEmptyTable": "表中数据为空",
                    "sLoadingRecords": "载入中...",
                    "sInfoThousands": ",",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": "上页",
                        "sNext": "下页",
                        "sLast": "末页"
                    },
                    "oAria": {
                        "sSortAscending": ": 以降序排列此列",
                        "sSortDescending": ": 以升序排列此列"
                    }
                }
            };
            $(dom).on('processing.dt', function (e, settings, processing) {
                if (processing) {
                    layer.load();
                } else {
                    layer.closeAll();
                }
            }).dataTable(dataOptions);
        }
    }


    $(document).on('submit', 'form.ajax-submit', function (e) {
        if (request) {
            return false;
        }
        //ajax表单提交
        var form = this;
        window.targetDom = form;
        e.preventDefault();
        var load = layer.load(),
            url = $(form).attr('action') || location.href;
        request = true;
        $.ajax({
            url: url,
            dataType: 'json',
            type: $(form).attr('method') || 'get',
            data: new FormData(form),
            processData: false,
            contentType: false,
            error: function (xhr) {
                request = false;
                layer.close(load);
                layer && layer.open({area: ['500px', '400px'], content: xhr.responseText});
            },
            success: function (resp) {
                request = false;
                layer.close(load);
                var returnUrl = $(form).attr('return-url') || resp.redirectUrl;
                if (resp.status == 'SUCCESS') {
                    layer.open({
                        title: '提示'
                        , content: resp.msg
                        , yes: function (index) {
                            this.cancel(index);
                        }
                        , cancel: function (index) {
                            layer.close(index);
                            if (returnUrl) location.href = returnUrl;
                        }
                    });

                } else {
                    if (resp.errbtn) {
                        var errobj = $(form).find('[name="' + resp.errbtn + '"]');
                        layer && layer.tips(resp.msg, errobj);
                        errobj.focus();
                    } else {
                        layer.msg(resp.msg);
                    }
                }
            }
        });
    }).on('click', '.sort-list', function (e) {
        //排序点击事件
        e.preventDefault();
        window.targetDom = this;
        var load = layer.load();
        var param = [];
        $('.sort-input').each(function () {
            var id = $(this).attr('pk');
            var sort = $(this).val();
            if (id) {
                param.push({id: id, sort: sort});
            }
        });
        var url = location.href;
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data: {sort: param},
            error: function (xhr) {
                layer.close(load);
                layer.open({area: ['500px', '400px'], content: xhr.responseText});
            },
            success: function (resp) {
                layer.close(load);
                if (resp.status == 'SUCCESS') {
                    location.reload();
                } else {
                    layer.msg(resp.msg);
                }
            }
        })
    }).on('click', '.ajax-click', function (e) {
        //ajax点击事件
        e.preventDefault();
        window.targetDom = this;
        var url = $(this).attr('data-url');
        if (url) {
            $.getJSON(url, function (resp, status, xhr) {
                if (resp.status == 'SUCCESS') {
                    layer.msg(resp.msg);
                    if (resp.redirectUrl) {
                        location.href = resp.redirectUrl;
                    }
                    var callback = $(e.toElement).attr('data-callback');
                    if (callback) {
                        eval(callback);
                        return true;
                    }
                    // 回调
                    if (resp.callback) {
                        $(document).triggerHandler('callback', resp.callback);
                        return true;
                    }
                } else {
                    resp.msg ? layer.alert(resp.msg) : layer.open({content: xhr.responseText});
                }
            })
        }
    });
});